<?php

namespace app\shop\logic;

use app\admin\logic\BasicLogic;
use app\data\util\HttpUtil;
use think\facade\Db;

use think\facade\Cache;
use util\Excel;
use think\exception\ValidateException;
use think\facade\Log;
use util\Token;
use util\Upload;
use think\cache\driver\Redis;

class ShopLogic extends BasicLogic
{

    /**
     * @desc  获取店铺信息
     * @author luckyXiong
     * @date   2024-07-02
     */
    public function getShopsList($params = [])
    {

        $shop_id   = $params['shop_id'] ?? '';
        $limit     = $params['limit'] ?? 10;
        $status    = $params['status']?? '';
        $site      = $params['site']?? '';

        $where = [];
        $order = [];
        if ($shop_id) {
            $where[] = ['id', '=', $shop_id];
        }

        $where[] = ['status', '=', 1];

        if($status){
            $where[] = ['status', '=', $status];
        }

        if($site){
            $where[] = ['site', '=', $site];
        }

        $res = Db::name('shops')
            ->field('*,name as shop_name')
            ->where($where)
            ->order($order)
            ->paginate($limit);

        $list = $res->items()?:[];
        $list = objectToArray($list);
        $data = [
            'list'   => $list,
            'total'  => $res->total(),
        ];
        return json(DefaultResponse(200, true, '获取成功', $data));
    }



    /**
     * @desc 更新店铺信息
     * @date 2024-04-24
     */
    public function update_shop_info($params=[]){
        $shop_id        = $params['shop_id']??'';
        $shop_info      = Db::name('shops')->where('id',$shop_id)->find();
        $version        = Config('Logisticskey.shopify.api_versoin');
        $operation      = Config('Logisticskey.shopify.shop_path');
        $url            = $shop_info['myshopify_domain'].$version . $operation;
        $data           = HttpUtil::geturl($url, $shop_info);

        p($data);die;

        if(isset($data['errors'])){
            Db::name('shops')->where('id',$shop_id)->update(
                [
                    'status' => $data['errors'] == 'Unavailable Shop' ? 2 :3,
                ]
            );
        }
        if(isset($data['shop']) && $data['shop']){
            $info = $data['shop'];
            Db::name('shops')->where('id',$shop_id)->update(
                [
                    'name'       =>$info['name'],
                    'email'      =>$info['email'],
                    'domain'     =>$info['domain'],
                    'timezone'   =>$info['timezone'],
                    'site'       =>$info['country_code'],
                    'created_time'=>date("Y-m-d H:i:s", strtotime($info['created_at']))
                ]
            );
        }
        return json(DefaultResponse(200, true, '操作成功', ''));
    }



    /**
     * @desc   获取店铺信息
     * @date   2024-07-03
     * @param  $shop_id
     * @return array|mixed
     * @author zhangheng
     */
    public function getShopInfo()
    {
        $data = Db::name('shops')
            ->field('id as shop_id,name as shop_name')
            ->where('status',1)
            ->select()
            ->toarray();
        $return['list'] = $data;
        return json(DefaultResponse(200, true, '获取成功', $return));
    }
    /**
     * @desc   开户主体列表
     * @date   2024-10-03
     * @author zhangheng
     */
    public function CompanyList($params=[])
    {
        $name         = $params['name']??'深圳';
        if($name){
            $where[] = ['advertiser_name', 'like', '%'.$name.'%'];
        }
        $return = Db::name('advaccount')
            ->field('id,advertiser_name as name')
            ->where($where)
            ->group('name')
            ->select()->toarray();
        return json(DefaultResponse(200, true, '获取成功', $return));
    }


    /**
     * @desc  获取运营列表
     * @author zhangheng
     * @date   2024-07-02
     */
    public function getSalesmanList($params = [])
    {
        $data = Db::name('system_admin')
            ->field('id,nickname,phone')
            ->where('group_ids',11)
            ->select()
            ->toarray();
        $data2['id'] = 1000;
        $data2['nickname'] = "未指定运营";
        $data2['phone'] = 0;
        array_unshift($data,$data2);
        $return['list'] = $data;
        return json(DefaultResponse(200, true, '获取成功', $return));
    }




    /**
     * @desc   获取在职运营列表
     * @author zhangheng
     * @date   2024-10-22
     */
    public function getOnSales($params = [])
    {
        $tel             = $params['tel']??'';
        $username        = $params['username']??'';
        $where           = [];
        if($username){
            $username = trim($username);
            $where[] = ['username', 'like', '%' . $username . '%'];
        }

        if($tel){
            $tel     = trim($tel);
            $where[] = ['phone', 'like', '%' . $tel . '%'];
        }
        $where[] = ['group_ids','=',11];
        $where[] = ['status','=',1];

        $list = Db::name('system_admin')
            ->field('id,nickname,phone')
            ->where($where)
            ->select()
            ->toarray();

        $list2['id'] = 100000;
        $list2['nickname'] = "未指定运营";
        $list2['phone'] = 0;
        array_unshift($list,$list2);

        return json(DefaultResponse(200, true, '获取成功', $list));
    }

    public function add($data = [])
    {
        if (!$data) {
            return json(DefaultResponse(201, false, '参数不能为空!', null));
        }
        $result = false;
        Db::startTrans();
        try {
            //广告账户
            $insert['email'] = $data['email'] ?? "";
            $insert['name'] = $data['shop_name'] ?? "";
            $insert['site'] = $data['site'] ?? "";
            $insert['type'] = $data['type'] ?? "";
            if($data['api'] == 1){
                $insert['myshopify_domain'] = $data['myshopify_domain'] ?? "";
                $insert['app_key'] = $data['app_key'] ?? "";
            }
            $insert['app_secret'] = $data['app_secret'] ?? "";
            
            $result = Db::name('shops')->insert($insert);
            if ($result !== false) { 
                Db::commit();
                return json(DefaultResponse(200, true, '添加成功!', null));
            }
            Db::rollback();
            return json(DefaultResponse(201, false, '添加失败!', null));
        } catch (ValidateException $e) {
            Db::rollback();
            return json(DefaultResponse(201, false, $e->getError(), null));
        } catch (\Exception $e) {
            Db::rollback();
            return json(DefaultResponse(201, false, $e->getMessage(), null));
        }
        return json(DefaultResponse(200, false, '添加成功!', null));
    }


    /**
     * @desc   店铺编辑
     * @author luckyXiong
     * @date   2024-07-15
     */
    public function edit_list($params = [])
    {
        $id         = $params['id']??'';
        if(!$id){
            return $this->jsonMessage(201,false,'ID不能为空',null);
        }
        $shop_name =  $params['shop_name']??'';
        $email     =  $params['email']??'';
        $status    =  $params['status']??'';
        $site      =  $params['site']??'';
        $type      =  $params['type']??'';
        $update    = [
            'name'   =>$shop_name,
            'email'  =>$email,
            'site'   =>$site,
            'status' =>$status,
            'type' =>$type,
        ];

        //广告账户
        if($params['api'] == 1){
            $update['myshopify_domain'] = $params['myshopify_domain'] ?? "";
            $update['app_key'] = $params['app_key'] ?? "";
            $update['app_secret'] = $params['app_secret'] ?? "";
        }
        htmlLog(['shops'=>$update],OPERATE_LOG . date('Ym') . '/shopsupdate/' . date('Ymd') . '.txt');
        Db::name('shops')->where('id',$id)->update($update);
        return $this->jsonMessage(200, true, '编辑成功',null);
    }


    /**
     * @desc   获取站点下拉数据
     * @author luckyXiong
     * @date   2024-08-05
     */
    public function getSiteList(){
        $info = Config('Logisticskey.site');
        $info = getLevel($info);
        $arr  = [];
        foreach($info as $v){
            $arr[] = [
                'warehouse_id'   => $v['key'],
                'warehouse_name' => $v['value'],
            ];
        }
        return $this->jsonMessage(200, true, '获取成功',$arr);
    }




    /**
     * @desc   获取在职运营列表接口
     * @author luckyXiong
     * @date   2024-10-05
     */
    public function getSaleOn(){
        $where   =  [];
        $where[] = ['employees_status','=',1];
        $where[] = ['group_ids','in',[11,15]];
        $list =  Db::name('system_admin')->field('id as admin_id,username as admin_name')
            ->where($where)
            ->select()->toArray();
        return $this->jsonMessage(200, true, '获取成功',$list);
    }









    /**
     * @desc   AscriptionList归属列表
     * @author zhangheng
     * @date   2024-08-09
     */
    public function AscriptionList($params){
        $limit = $params['limit'] ?? 10;
        $shop_id = $params['shop_id'] ?? "";
        $admin_id = $params['admin_id'] ?? "";

        $where = [];
        if(!empty($shop_id)){
            $where[] = ['a.shop_id', '=', $shop_id];
        }
        if(!empty($admin_id)){
            $where[] = ['a.admin_id', '=', $admin_id];
        }
        
        $list = Db::name('shops_admin')
            ->field('
                a.id,
                a.shop_id,
                a.admin_id,
                a.createtime,
                a.type as type_id,
                a.label,
                a.updatetime,a.status,
                c.nickname as admin_name,
                d.name as shop_name
            ')
            ->alias('a')
            ->join('qu_system_admin c','c.id = a.admin_id', 'left')
            ->join('qu_shops d','d.id = a.shop_id', 'left')
            ->where($where)
            ->order("a.shop_id desc,a.updatetime desc")
            ->paginate($limit);
        $lists = $list->items();
        foreach ($lists as $k=>$v) {
            $lists[$k]['createtime'] = date('Y-m-d',$v['createtime']);
            if(!empty($v['updatetime'])){
                $lists[$k]['updatetime'] = date('Y-m-d',$v['updatetime']);
            }else{
                $lists[$k]['updatetime'] = "至今";
            }
            switch ($v['type_id']) {
                case '1':
                    $lists[$k]['type'] = '单人使用';
                    break;
                case '2':
                    $lists[$k]['type'] = '多人使用';
                    break;
                default:
                    $lists[$k]['type'] = '未知';
            }
            
        }
        
        $data = [
            'list' => $lists,
            'total' => $list->total(),
        ];
        return json(DefaultResponse(200, true, '获取成功', $data));
    }

    public function AscriptionAdd($data = [])
    {
        if (!$data) {
            return json(DefaultResponse(201, false, '参数不能为空!', null));
        }
        $result = false;

        try {
            $insert['admin_id'] = $data['admin_id'] ?? 0;
            $insert['shop_id'] = $data['shop_id'] ?? 0;
            $insert['type'] = $data['type_id'] ?? 0;
            $insert['label'] = $data['label'] ?? "";

            $insert['createtime'] = 0;
            $insert['status'] = 1;
            $insert['updatetime'] = 0;
            if (!empty($data['createtime'])) {
                $insert['createtime'] = strtotime($data['createtime']);
            }
            if (!empty($data['updatetime'])) {
                $insert['status'] = 0;
                $insert['updatetime'] = strtotime($data['updatetime']);
            }
            $result = Db::name('shops_admin')->insert($insert);
            
            if ($result !== false) {
                return json(DefaultResponse(200, true, '添加成功!', null));
            } else {
                return json(DefaultResponse(201, false, '添加失败!', null));
            }
        } catch (ValidateException $e) {
            return json(DefaultResponse(201, false, $e->getError(), null));
        } catch (\Exception $e) {
            return json(DefaultResponse(201, false, $e->getMessage(), null));
        }
        return json(DefaultResponse(200, false, '更新成功!', null));

    }

    public function AscriptionEdit($data = [])
    {
        if (!$data) {
            return json(DefaultResponse(201, false, '参数不能为空!', null));
        }
        $id = $data['id'];
        if (empty($id)) {
            return json(DefaultResponse(201, false, '数据不存在!', null));
        }
        $result = false;

        try {
            $update['admin_id'] = $data['admin_id'] ?? 0;
            $update['shop_id'] = $data['shop_id'] ?? 0;
            $update['type'] = $data['type_id'] ?? 0;
            $update['label'] = $data['label'] ?? "";

            $update['createtime'] = 0;
            $update['updatetime'] = 0;
            if (!empty($data['createtime'])) {
                $update['createtime'] = strtotime($data['createtime']);
            }
            if (!empty($data['updatetime'])) {
                $update['status'] = 0;
                $update['updatetime'] = strtotime($data['updatetime']);
            }
            $result = Db::name('shops_admin')->where('id',$id)->update($update);

            if ($result) {
                return json(DefaultResponse(200, false, '更新成功!', null));
            }
            return json(DefaultResponse(201, false, '更新失败!', null));
        } catch (ValidateException $e) {
            return json(DefaultResponse(201, false, $e->getError(), null));
        } catch (\Exception $e) {
            return json(DefaultResponse(201, false, '更新失败!', null));
        }
        return json(DefaultResponse(200, false, '更新成功!', null));
    }



}